package com.example.lprxjava;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Author by lp,on 2021/7/1/001,14:20.
 */
abstract class BaseFragment extends Fragment {
    private  final String TAG = getTAG();
    protected Observable<Object> observable;
    protected TextView textView;
    protected StringBuffer stringBuffer = new StringBuffer();
    private View view;

    abstract String getTitle();
    abstract String getTAG();

    abstract void onLoad(View view);

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(getFragmentLayoutId(), container, false);
        textView = view.findViewById(R.id.tv_show);
        onLoad(view);
        return view;
    }

    abstract int getFragmentLayoutId();

    protected View getFragmentView() {
        return view;
    }

    //观察者
    protected Observer observer = new Observer<Object>() {

        @Override
        public void onSubscribe(Disposable d) {
            Log.i(TAG, "onSubscribe: Thread: " + Thread.currentThread().getName());
        }

        @Override
        public void onNext(Object o) {
            Log.i(TAG, "observer Thread: " + Thread.currentThread().getName());
            Log.i(TAG, "onNext: " + o);
            stringBuffer.append(o.toString() + "\r\n");
            showText();
        }

        @Override
        public void onError(Throwable e) {
            Log.i(TAG, "onError: " + e.getMessage());

        }

        @Override
        public void onComplete() {
            Log.i(TAG, "onComplete: ");
        }
    };

    protected void showText() {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText(stringBuffer.toString());
                }
            });
        }
    }

}
